package com.jiang.redis.redisson;

import java.util.concurrent.TimeUnit;

import org.junit.Test;
import org.redisson.RedissonLock;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author jiangwz
 * @create 2019/3/11.
 */
public class RedissonTest {
    private static final Logger log = LoggerFactory.getLogger(RedissonLock.class);

    @Test
    public void test(){
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    System.out.println(Thread.currentThread().getName() + " 开始执行");
                    boolean test = RedissonUtils.tryLock("test", TimeUnit.SECONDS, 6, 20);
                    if (test){
                        RLock test1 = RedissonUtils.lock("test", TimeUnit.SECONDS, 5);
                        System.out.println(Thread.currentThread().getName() + " 获取锁");
                        try {
                            Thread.sleep(4000);
                        } catch (InterruptedException e) {
//                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + " 释放锁");
                        RedissonUtils.unlock(test1);//加了这个释放锁好像有点问题 睡眠时间小于锁的时间就会出问题
                    }else {
                        System.out.println(Thread.currentThread().getName() + " 未抢到锁");
                    }
                }
            },"test"+i).start();
        }

        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {

        }
    }

    @Test
    public void test02(){
        String key = "test";

        boolean test = RedissonUtils.tryLock("test", TimeUnit.SECONDS, 6, 20);
        log.info("tryLock");
        if (test) {
            log.info("lock");
            RLock lock = RedissonUtils.lock(key, TimeUnit.SECONDS, 5);
            try {
                RedissonUtils.lock(key, TimeUnit.SECONDS, 5);
                RedissonUtils.lock(key, TimeUnit.SECONDS, 5);
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("unlock");
            RedissonUtils.unlock(lock);
        }
    }

    @Test
    public void test03() throws InterruptedException {
        String key = "test1";
        RLock lock = RedissonUtils.lock(key, TimeUnit.SECONDS, 60);
        TimeUnit.SECONDS.sleep(20);
        System.out.println("开始可重入");
        RedissonUtils.lock(key, TimeUnit.SECONDS, 60);
        RedissonUtils.lock(key, TimeUnit.SECONDS, 60);
        RedissonUtils.lock(key, TimeUnit.SECONDS, 60);
        RedissonUtils.lock(key, TimeUnit.SECONDS, 60);
        RedissonUtils.lock(key, TimeUnit.SECONDS, 60);
        RedissonUtils.lock(key, TimeUnit.SECONDS, 60);

        RedissonUtils.unlock(lock);
        System.out.println("开始释放锁");
        TimeUnit.SECONDS.sleep(20);
    }
}
